package com.jmoney.luckeylink.handler;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.testng.Assert;
import org.testng.Reporter;

import com.jmoney.luckeylink.controller.LekeU_Captcha_Controller;
import com.jmoney.luckeylink.controller.LekeU_Login_Controller;
import com.jmoney.luckeylink.util.ExcelUtil;
import com.jmoney.luckeylink.util.MobileApiToolsUtil;
import com.jmoney.luckeylink.util.DecodeUnicodeUtil;

public class LekeU_Login_Handler {
    private static Logger logger = Logger.getLogger(LekeU_Login_Handler.class);
    static int TITLE_LINE_INDEX=6;
    static String Param = null;
    
	/**
	 * <br>获取Excel数据</br>
	 * @author  刘智King
	 * @date     2018年4月20日 下午6:01:04
	 */
    public static void GetExcelInstance() {
        logger.info(LekeU_Login_Handler.class);
        System.out.println(LekeU_Login_Handler.class);
		ExcelUtil.getInstance().setFilePath("src/test/java/TestCasexls/JMoney.Luckeylink.Api.xlsm");
		ExcelUtil.getInstance().setSheetName("LekeU_Login");
    }
    
	/**
	 * <br>初始化Excel数据</br>
	 * @author  刘智King
	 * @date     2018年4月20日 下午6:01:04
	 */
    public static void InitializeExcelData() { 
    	int color = 4;
        try {
            logger.info("初始化: " + ExcelUtil.getInstance().getFilePath() + ", " + ExcelUtil.getInstance().getSheetName());
            System.out.println("初始化: " + ExcelUtil.getInstance().getFilePath() + ", " + ExcelUtil.getInstance().getSheetName());
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "Run", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "message_Act", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "id_Act", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "name_Act", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "id_card_Act", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "occupation_Act", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "address_Act", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "type_Act", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "blood_type_Act", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "id_card_photo_positive_Act", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "id_card_photo_negative_Act", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "StatusCode", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "TestResult", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "RunningTime", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "Json", "", color);
            MobileApiToolsUtil.initializeData(TITLE_LINE_INDEX, "FailHint", "", color);
            logger.info(ExcelUtil.getInstance().getFilePath() + ", " + ExcelUtil.getInstance().getSheetName() + "初始化完成");
            System.out.println(ExcelUtil.getInstance().getFilePath() + ", " + ExcelUtil.getInstance().getSheetName() + "初始化完成");
            System.out.println("==================================================================");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

	/**
	 * <br>根据数据库版本和用例ID，从数据库获取信息并写入到Excel预期值</br>
	 * @author  刘智King
	 * @date     2018年4月20日 下午6:01:04
	 * @param  DataVersion
	 * @param  ID
	 */
    public static void WriteExcelExpected(String DataVersion,int ID){ 
    	
    	List<Map<String, String>> data = null;
        data = ExcelUtil.getInstance().readExcelAllData(TITLE_LINE_INDEX);
        
        try {
        	if (data != null) {
//                for (int i = 0; i < data.size(); i++) {
        		  int i = ID;
        	      Map<String, String> map = data.get(i);
                  String Sql =map.get("userId");

                  logger.info("根据数据库查询结果, 开始写入预期值【Waiting...】");
                  System.out.println("根据数据库查询结果, 开始写入预期值【Waiting...】");
                  
//                  String $id_Exp= DataBase_Util.GetSqlResult(DataVersion, Sql,"$id_Exp");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "$id_Exp", "2");
        	      
        	      String phone_Exp= LekeU_Captcha_Controller.GetSqlResult(DataVersion, Sql,"phone");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "phone_Exp", phone_Exp);

        	      String roleId_Exp= LekeU_Captcha_Controller.GetSqlResult(DataVersion, Sql,"roleId");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "roleId_Exp", roleId_Exp);
        	
        	      String roleName_Exp= LekeU_Captcha_Controller.GetSqlResult(DataVersion, Sql,"roleName");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "roleName_Exp", roleName_Exp);
        	      
        	      String salesId_Exp= LekeU_Captcha_Controller.GetSqlResult(DataVersion, Sql,"salesId");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "salesId_Exp", salesId_Exp);
        	      
        	      String userName_Exp= LekeU_Captcha_Controller.GetSqlResult(DataVersion, Sql,"userName");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "userName_Exp", userName_Exp);
        	      
//        	      String identification_Exp= DataBase_Util.GetSqlResult(DataVersion, Sql,"identification");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "identification_Exp", "string");
        	      
        	      String photoName_Exp= LekeU_Captcha_Controller.GetSqlResult(DataVersion, Sql,"photoName");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "photoName_Exp", "http://10.10.11.136/"+photoName_Exp);
        	      
                 logger.info("对应用例预期值,写入成功【OK】");
                 System.out.println("对应预期值,写入成功【OK】");
                 System.out.println("==================================================================");
               }
//            } 
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
    
	/**
	 * <br>根据用例ID，执行Login相关接口请求，获取Json信息，并写入结果到Excel</br>
	 * @author  刘智King
	 * @date     2018年4月20日 下午6:01:04
	 * @param  ID
	 */
    public static void Login(int ID) throws Exception {

        boolean ArgName = false;
        List<Map<String, String>> data = null;
        
        String PremiseUrl = ExcelUtil.getInstance().readExcelCell(1, 2);
        String ApiUrl = ExcelUtil.getInstance().readExcelCell(2, 2);
        String Act = ExcelUtil.getInstance().readExcelCell(3, 2);
        String Method = ExcelUtil.getInstance().readExcelCell(4, 2);
        ArgName = MobileApiToolsUtil.isArgEquals(5, 2, TITLE_LINE_INDEX);

        if (PremiseUrl.equals("") ||ApiUrl.equals("") || Act.equals("") || Method.equals("") || !ArgName) {
            logger.error("请检查 Excel 中 PremiseUr、ApiUrl、Act、Method、ArgName 是否设置正确...");
            System.out.println("请检查 Excel 中 PremiseUr、ApiUrl、Act、Method、ArgName 是否设置正确...");
            System.exit(-1);
        }

        data = ExcelUtil.getInstance().readExcelAllData(TITLE_LINE_INDEX);

        if (data != null) {
            int i = ID;
            //根据Excel列名称,获取单元格内容
            Map<String, String> map = data.get(i-1);
            String CaseID = map.get("CaseID");
            String CaseName = map.get("CaseName");
            String type = map.get("type");
            String mobile = map.get("mobile");
            String captcha = map.get("captcha");
            
            //写入Run列, 执行纪录
            MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "Run", "Y");

            //指定请求的Api地址
            String LoginUrl = PremiseUrl+"?"+"type="+type+"&mobile="+mobile+"&captcha="+captcha+"";
            Object[] LoginInfo = LekeU_Login_Controller.GetLoginInfo(LoginUrl);
            String token = (String) LoginInfo[3];
            
            //指定请求的Api地址
            Param = "token="+token+"";
            String DetailUrl = ApiUrl+"?"+Param;
            
            //请求接口，获取UserDetail数组
            Object[] UserDetail = LekeU_Login_Controller.GetUserDetail(DetailUrl);

            //从UserDetail数组中，读取StatusCode并写入
            int StatusCode = (int) LoginInfo[1];
            MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "StatusCode", String.valueOf(StatusCode));
            
            //判断StatusCode结果是否等于200，成立则TestResult写入OK并设置单元格颜色为绿色，反则写入NG并设置单元格颜色为红色，并写入失败消息提示
            if (StatusCode == 200){
            	ExcelUtil.getInstance().setCellBackgroundColor(TITLE_LINE_INDEX, "StatusCode",TITLE_LINE_INDEX + i, 1);
            	MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "TestResult", "OK");
                ExcelUtil.getInstance().setCellBackgroundColor(TITLE_LINE_INDEX, "TestResult",TITLE_LINE_INDEX + i, 1);
            }else{
            	ExcelUtil.getInstance().setCellBackgroundColor(TITLE_LINE_INDEX, "StatusCode",TITLE_LINE_INDEX + i, 0);
            	MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "TestResult", "NG");
            	ExcelUtil.getInstance().setCellBackgroundColor(TITLE_LINE_INDEX, "TestResult",TITLE_LINE_INDEX + i, 0);
            	//从UserDetail数组中，读取message消息结果并写入
                String message = (String) LoginInfo[2];
                MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "FailHint", "【message】"+message+"");
            }

            //写入执行时间
            MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "RunningTime", MobileApiToolsUtil.getDate());

            //从UserDetail数组中，读取JSON结果并编码转换后写入
            String Json = (String) LoginInfo[0];
            String NewJson=DecodeUnicodeUtil.decodeUnicode(Json);
            MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "Json", NewJson);
            
            //从UserDetail数组中，读取message_Act结果并写入       
            String message_Act = (String) LoginInfo[2];
            MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "message_Act", message_Act);
            
            if("ok".equals(message_Act)){
            	//从UserDetail数组中，读取id_Act结果并写入       
                int id_Act = (int) UserDetail[3];
                MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "id_Act", String.valueOf(id_Act));
                
                //从UserDetail数组中，读取name_Act结果并写入       
                String name_Act = (String) UserDetail[4];
                MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "name_Act", name_Act);
                
                //从UserDetail数组中，读取id_card_Act结果并写入       
                String id_card_Act = (String) UserDetail[5];
                MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "id_card_Act", id_card_Act);

                //从UserDetail数组中，读取mobile_Act结果并写入       
                String mobile_Act = (String) UserDetail[6];
                MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "mobile_Act", mobile_Act);

                //从UserDetail数组中，读取occupation_Act结果并写入       
                String occupation_Act = (String) UserDetail[7];
                MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "occupation_Act", occupation_Act);
                
                //从UserDetail数组中，读取address_Act结果并写入       
                String address_Act = (String) UserDetail[8];
                MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "address_Act", address_Act);
                
                //从UserDetail数组中，读取type_Act结果并写入       
                int type_Act = (int) UserDetail[9];
                MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "type_Act", String.valueOf(type_Act));
                
                //从UserDetail数组中，读取blood_type_Act结果并写入       
                String blood_type_Act = (String) UserDetail[10];
                MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "blood_type_Act", blood_type_Act);
                
                //从UserDetail数组中，读取id_card_photo_positive_Act结果并写入       
                int id_card_photo_positive_Act = (int) UserDetail[11];
                MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "id_card_photo_positive_Act", String.valueOf(id_card_photo_positive_Act));
                
                //从UserDetail数组中，读取id_card_photo_negative_Act结果并写入       
                int id_card_photo_negative_Act = (int) UserDetail[12];
                MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "id_card_photo_negative_Act", String.valueOf(id_card_photo_negative_Act));
                
                String id_Exp = map.get("id_Exp");
                String name_Exp = map.get("name_Exp");
                String id_card_Exp = map.get("id_card_Exp");
                String mobile_Exp = map.get("mobile_Exp");
                String occupation_Exp = map.get("occupation_Exp");
                String address_Exp = map.get("address_Exp");
                String type_Exp = map.get("type_Exp");
                String blood_type_Exp = map.get("blood_type_Exp");
                String id_card_photo_positive_Exp = map.get("id_card_photo_positive_Exp");
                String id_card_photo_negative_Exp = map.get("id_card_photo_negative_Exp");
                
                Reporter.log("用例ID: "+ CaseID);        
    	        Reporter.log("用例名称: "+ CaseName);
    	        Reporter.log("请求地址: "+ ApiUrl);
    	        Reporter.log("请求方式: "+ Method);
    	        Reporter.log("请求参数: "+ Param);
    	        Reporter.log("返回结果: "+ NewJson);
    	        
                //检查预期结果和实际结果是否正确
    	        checkEquals(id_Exp,String.valueOf(id_Act),"id_Exp","id_Act",ID);	 
    	        checkEquals(name_Exp,String.valueOf(name_Act),"name_Exp","name_Act",ID);	   
    	        checkEquals(id_card_Exp,String.valueOf(id_card_Act),"id_card_Exp","id_card_Act",ID);	 
    	        checkEquals(mobile_Exp,String.valueOf(mobile_Act),"mobile_Exp","mobile_Act",ID);	 
    	        checkEquals(occupation_Exp,String.valueOf(occupation_Act),"occupation_Exp","occupation_Act",ID);	 
    	        checkEquals(address_Exp,String.valueOf(address_Act),"address_Exp","address_Act",ID);	 
    	        checkEquals(type_Exp,String.valueOf(type_Act),"type_Exp","type_Act",ID);	 
    	        checkEquals(blood_type_Exp,String.valueOf(blood_type_Act),"blood_type_Exp","blood_type_Act",ID);	 
    	        checkEquals(id_card_photo_positive_Exp,String.valueOf(id_card_photo_positive_Act),"id_card_photo_positive_Exp","id_card_photo_positive_Act",ID);	 
    	        checkEquals(id_card_photo_negative_Exp,String.valueOf(id_card_photo_negative_Act),"id_card_photo_negative_Exp","id_card_photo_negative_Act",ID);
            }else{
            	Reporter.log("用例ID: "+ CaseID);        
    	        Reporter.log("用例名称: "+ CaseName);
    	        Reporter.log("请求地址: "+ ApiUrl);
    	        Reporter.log("请求方式: "+ Method);
    	        Reporter.log("请求参数: "+ Param);
    	        Reporter.log("返回结果: "+ NewJson);
    	        
            	String message_Exp = map.get("message_Exp");
    	        checkEquals(message_Exp,message_Act,"message_Exp","message_Act",ID);	 
            }
        }
    }

	/**
	 * <br>根据用例ID，检查预期与实际是否相等，不等则提示错误信息，并写入结果</br>
	 * @author  刘智King
	 * @date     2018年4月20日 下午6:01:04
	 * @param  ID
	 */
	public static void checkEquals(String Expected,String Actual,String ExpectedList,String ActualList,int ID) throws Exception{
		int i = ID;
		try {
			Assert.assertEquals(Expected,Actual);
			MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "TestResult", "OK");
            ExcelUtil.getInstance().setCellBackgroundColor(TITLE_LINE_INDEX, "TestResult",TITLE_LINE_INDEX + i, 1);
			Reporter.log("用例结果: 〖"+ExpectedList.replace("_Exp", "")+"〗=>Expected: " + "【"+Expected+"】" + ", Actual: "+ "【"+Actual+"】");
	        System.out.println("用例结果: 【"+ExpectedList.replace("_Exp", "")+"】=>Expected: " + "【"+Expected+"】" + ", Actual: "+ "【"+Actual+"】");
        }catch (Error e)  {
 	    	MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "TestResult", "NG");
        	ExcelUtil.getInstance().setCellBackgroundColor(TITLE_LINE_INDEX, "TestResult",TITLE_LINE_INDEX + i, 0);
 	    	ExcelUtil.getInstance().setCellBackgroundColor(TITLE_LINE_INDEX, ActualList,TITLE_LINE_INDEX + i, 3);
 	    	MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "FailHint", "【"+ExpectedList+"】和【"+ActualList+"】不一致");
 	    	Assert.fail(""+ExpectedList.replace("_Exp", "")+" =>Expected 【"+ Expected +"】"+" "+"but found 【"+ Actual +"】");
 	    }
	}
	
	/**
	 * <br>根据用例ID，获取用例名称信息，打印到控制台并写入Excel</br>
	 * @author  刘智King
	 * @date     2018年4月20日 下午6:01:04
	 * @param  ID
	 */
    public static void GetCaseInfo(int ID) throws Exception {
    	
    	List<Map<String, String>> data = null;
    	data = ExcelUtil.getInstance().readExcelAllData(TITLE_LINE_INDEX);

    	if (data != null) {
                int i = ID;
            	//根据Excel列名称,获取单元格内容
                Map<String, String> map = data.get(i-1);
                String CaseID = map.get("CaseID");
                String CaseName = map.get("CaseName");
  
                String message_Exp = map.get("message_Exp");
                String id_Exp = map.get("id_Exp");
                String name_Exp = map.get("name_Exp");
                String id_card_Exp = map.get("id_card_Exp");
                String mobile_Exp = map.get("mobile_Exp");
                String occupation_Exp = map.get("occupation_Exp");
                String address_Exp = map.get("address_Exp");
                String type_Exp = map.get("type_Exp");
                String blood_type_Exp = map.get("blood_type_Exp");
                String id_card_photo_positive_Exp = map.get("id_card_photo_positive_Exp");
                String id_card_photo_negative_Exp = map.get("id_card_photo_negative_Exp");
                
                String message_Act = map.get("message_Act");
                String id_Act = map.get("id_Act");
                String name_Act = map.get("name_Act");
                String id_card_Act = map.get("id_card_Act");
                String mobile_Act = map.get("mobile_Act");
                String occupation_Act = map.get("occupation_Act");
                String address_Act = map.get("address_Act");
                String type_Act = map.get("type_Act");
                String blood_type_Act = map.get("blood_type_Act");
                String id_card_photo_positive_Act = map.get("id_card_photo_positive_Act");
                String id_card_photo_negative_Act = map.get("id_card_photo_negative_Act");
                
                String StatusCode = map.get("StatusCode");
                String TestResult = map.get("TestResult");
                String FailHint = map.get("FailHint");

    	        //打印日志
    	        logger.info("CaseID: " + CaseID + ", CaseName: " + CaseName +  
    	        		", message_Exp: " + message_Exp +", message_Act: " + message_Act+ 
    	                ", id_Exp: " + id_Exp +", id_Act: " + id_Act+ 
    	                ", name_Exp: " + name_Exp +", name_Act: " + name_Act+
    	                ", id_card_Exp: " + id_card_Exp +", id_card_Act: " + id_card_Act+
    	                ", mobile_Exp: " + mobile_Exp +", mobile_Act: " + mobile_Act+
    	                ", occupation_Exp: " + occupation_Exp +", occupation_Act: " + occupation_Act+
    	                ", address_Exp: " + address_Exp +", address_Act: " + address_Act+
    	                ", type_Exp: " + type_Exp +", type_Act: " + type_Act+
    	                ", blood_type_Exp: " + blood_type_Exp +", blood_type_Act: " + blood_type_Act+
    	                ", id_card_photo_positive_Exp: " + id_card_photo_positive_Exp +", id_card_photo_positive_Act: " + id_card_photo_positive_Act+
    	                ", id_card_photo_negative_Exp: " + id_card_photo_negative_Exp +", id_card_photo_negative_Act: " + id_card_photo_negative_Act+
    	                ", StatusCode: " + StatusCode +", TestResult: " + TestResult + ", FailHint: " + FailHint + "");
    	        logger.info("==================================================================");

                 System.out.println("CaseID: " + CaseID + ", CaseName: " + CaseName +  
                		 ", message_Exp: " + message_Exp +", message_Act: " + message_Act+ 
                         ", id_Exp: " + id_Exp +", id_Act: " + id_Act+ 
                         ", name_Exp: " + name_Exp +", name_Act: " + name_Act+
                         ", id_card_Exp: " + id_card_Exp +", id_card_Act: " + id_card_Act+
                         ", mobile_Exp: " + mobile_Exp +", mobile_Act: " + mobile_Act+
                         ", occupation_Exp: " + occupation_Exp +", occupation_Act: " + occupation_Act+
                         ", address_Exp: " + address_Exp +", address_Act: " + address_Act+
                         ", type_Exp: " + type_Exp +", type_Act: " + type_Act+
                         ", blood_type_Exp: " + blood_type_Exp +", blood_type_Act: " + blood_type_Act+
                         ", id_card_photo_positive_Exp: " + id_card_photo_positive_Exp +", id_card_photo_positive_Act: " + id_card_photo_positive_Act+
                         ", id_card_photo_negative_Exp: " + id_card_photo_negative_Exp +", id_card_photo_negative_Act: " + id_card_photo_negative_Act+
                         ", StatusCode: " + StatusCode +", TestResult: " + TestResult + ", FailHint: " + FailHint + "");
                  System.out.println("==================================================================");   
            }
    }
}